#!/bin/sh
# fall back to this script if the waitmax binary is missing...

usage() {

	echo "
Usage: waitmax [-s SIGNUM] MAXTIME PROGRAM [ARGS...]

Execute PROGRAM as a subprocess. If PROGRAM does not exit before MAXTIME
seconds, it will be killed with SIGTERM or an alternative signal.

   -s, --signal SIGNUM   kill with SIGNUM on timeout
   -h, --help            this help
   -V, --version         show version an exit
"
	exit
}

SIGNUM=15 #SIGTERM

[ "$(echo $1)" = "" ] && usage

for i in $@ ; do
	case $1 in
		-V|--version) echo "waitmax version 1.0" ; exit ;;
		-h|-help|--help) usage ; exit ;;
		-s|--signal)
			if [ $2 -lt 1 -o $2 -gt 32 ] ; then
				echo "Signalnumber must be between 1 and 32."
				exit 1
			fi
			SIGNUM=$2
			shift 2
			;;
	esac
done

MAXTIME=$1
shift
PROG="$1"
shift
ARGS="$@"

[ $MAXTIME -lt 0 ] && usage
[ "$(echo $PROG)" = "" ] && usage

if [ "$ARGS" ] ; then
	"$PROG" "$ARGS" &
else
	"$PROG" &
fi
PID=$!

TIMEOUT=$MAXTIME

while [ $TIMEOUT -gt 0 ]
do
	busybox ps | awk '{print $1}' | grep -q "^${PID}$" || exit
	TIMEOUT=$((TIMEOUT-1))
	sleep 1
done

kill -n $SIGNUM $PID 

### END ###
